# Author: Lovy
# File : generalFunction
# Time : 2023-02-16 18:45
import random
import time

from PyGameAutoAndroid import *

from configs.config720 import *
from utils.handle_loguru import log


# 点击
def click(loc, duration=0.1, text=None):
    x1, y1, x2, y2 = loc
    if x1 < x2:
        x = random.randint(x1, x2)
    else:
        x = random.randint(x2, x1)
    if y1 < y2:
        y = random.randint(y1, y2)
    else:
        y = random.randint(y2, y1)
    time.sleep(0.3)
    xp.console("点击 坐标({}, {}), {}".format(x, y, text))
    log.info("点击 坐标({}, {}), {}".format(x, y, text))
    xp.tap(x, y, duration)
    time.sleep(2)


# 文字识别
def ocr(loc):
    time.sleep(0.3)
    x1, y1, x2, y2 = loc
    ret = xp.getText(x1, y1, x2, y2)
    if ret:
        return ret.text
    return None


# 检查文字是否存在
def check_ocr(ret, task_name="主线浮生若梦若"):
    if task_name:
        for i in task_name:
            if i in ret:
                return True
    return False


# 检查文字是否存在
def old_check_ocr(ret, task_name="主线浮生若梦若"):
    if task_name in ret:
        return True
    return False


# 循环找色
def loop_until(find_image, name, times=100, breakTime=3):
    # print(find_image[name])
    target = find_image[name]
    if len(target) == 6:
        mainColorDesc, multiColorDesc, x1, y1, x2, y2 = target
    else:
        mainColorDesc, multiColorDesc = target
        x1, y1, x2, y2 = (0, 0, 0, 0)

    while times > 0:
        ret = xp.findColor(mainColorDesc, multiColorDesc, x1, y1, x2, y2)
        # xp.console(ret)
        if ret:
            return ret
        times -= 1
        xp.console("多点找色：{}。。。".format(name))
        log.info("多点找色：{}。。。".format(name))
        time.sleep(breakTime)
    return False


# 循环找图
def loop_Image_until(args, times=100, not_all=True, breakTime: float = 3.0):
    image_name, loc = args
    if not_all:
        find_image = xp.findImage
    else:
        find_image = xp.findImageAll
    while times > 0:
        # 找图
        ret = find_image(image_name, *loc)
        # xp.console(ret)
        if ret:
            return ret
        times -= 1
        print(("循环找图：[{}]。。。".format(image_name)))
        log.info("循环找图：[{}]。。。".format(image_name))
        time.sleep(breakTime)


# 循环找字
def loop_words_until(words, x1: int = 0, y1: int = 0, x2: int = 0, y2: int = 0, times: int = 100, breakTime=3):
    while times > 0:
        # 找字
        ret = xp.findText(words, x1, y1, x2, y2)
        # xp.console("{},{}".format(words, ret))
        if ret:
            return ret.x, ret.y, ret.x + ret.width, ret.y + ret.height
        times -= 1
        print(("循环找字：[{}]。。。".format(words)))
        log.info("循环找字：[{}]。。。".format(words))
        time.sleep(breakTime)
    return False


# 活动栏识别
def old_ocr_task(task_names):
    if not task_names:
        return False
    start_x, start_y = main_task["location"]["start_loc"]
    rect_x, rect_y = main_task["location"]["rect"]
    width = main_task["location"]["width"]
    height = main_task["location"]["height"]
    for j in range(3):
        for i in range(2):
            x1, y1 = start_x + i * width, start_y + j * height
            x2, y2 = x1 + rect_x, y1 + rect_y
            time.sleep(1)
            if not xp.matchColor("#B5A69C", x1, y1):  # 确定任务是否存在
                ret = xp.getText(x1, y1, x2, y2)
                if ret:
                    for name in task_names:
                        if name in ret.text:
                            # 点击前往  判断是否可以点击前往
                            time.sleep(0.5)
                            # 多点找色
                            res1 = xp.findColor(*main_task["find_color"]["完成"], x1 + 170, y1 - 5, x1 + 210, y1 + 16)
                            # 单点比色 是否为完成的颜色
                            res2 = xp.matchColor("#F7EBD6", x1 + 184, y1 + 16)
                            # 文字识别
                            tt = ocr([x1 + 182, y1 + 18, x1 + 182 + 66, y1 + 18 + 24])
                            # 找图
                            res3 = xp.findImage("main_task/完成.png", x1 + 173, y1 - 5, x1 + 173 + 102, y1 - 5 + 50)
                            log.info("是否完成:{}, {}, {}, {}".format(res1, res2, res3, tt))
                            # TODO 判断人物是否完成  null,False,null,前往  [找图，返回多坐标有问题]
                            if not (res1 or res2 or res3):
                                click([x1 + 190, y1 + 5, x1 + 240, y1 + 20],
                                      text="点击前往 ({},{},{},{})".format(x1 + 190, y1 + 5, x1 + 240, y1 + 20))
                                return True
                            else:  # 任务已完成
                                click(main_task["cancel"], text="本轮任务完成 叉掉")
                                return False
                        else:
                            log.info("{}不在{}里面".format(name, ret.text))
                else:
                    log.info("未成功识别 任务栏 任务")
            else:
                log.info("没有东西")
                return False
    return False


def ocr_task(task_names="除暴"):
    ret = loop_words_until(task_names, *main_task["location"]["check_loc"], times=3)
    if ret:
        x1, y1 = ret[0], ret[1]
        # 判断是否可以点击前往
        # 多点找色
        res1 = xp.findColor(*main_task["find_color"]["完成"], x1 + 190, y1 + 5, x1 + 210, y1 + 16)
        # 单点比色 是否为完成的颜色
        res2 = xp.matchColor("#F7EBD6", x1 + 190, y1 + 2)
        # 文字识别
        tt = ocr([x1 + 182, y1 + 18, x1 + 182 + 66, y1 + 18 + 24])
        # 找图
        res3 = xp.findImage("main_task/完成.png", x1 + 170, y1 - 17, x1 + 170 + 105, y1 - 17 + 62)
        log.info("是否完成:{}, {}, {}, {}".format(res1, res2, res3, tt))
        if not (res1 or res2 or res3):
            click([x1 + 190, y1 + 5, x1 + 240, y1 + 20],
                  text="点击前往 ({},{},{},{})".format(x1 + 190, y1 + 5, x1 + 240, y1 + 20))
            return True
        else:  # 任务已完成
            click(main_task["cancel"], text="本轮任务完成 叉掉")
            return "完成"
    else:
        xp.console("没有找到 任务 %s" % task_names)
        log.info("没有找到 任务 %s" % task_names)
        return False





# 活动栏
def get_all_task_loc(task_names="除暴", old_task_names=None):
    time.sleep(5)
    # 点击
    click(mainUI["main_task_loc"], text="点击 活动")
    # 循环遍历 点击 如果找到 退出循环
    activity_loc = [
        main_task["activity"]["equipment"],
        main_task["activity"]["props"],
        main_task["activity"]["props_weapons"],
        main_task["activity"]["experience"],
        main_task["activity"]["all"]
    ]
    if old_check_ocr(["副本", "修行", "助人为乐"], task_names):
        click(activity_loc[0], text="点击 装备")
    elif old_check_ocr(["帮派任务", "帮派日常", "通天塔", "竞技场", "引魂入殿"], task_names):
        click(activity_loc[1], text="点击 道具")
    elif old_check_ocr(["通天塔", "魔龙之祸"], task_names):
        click(activity_loc[2], text="点击 道武")
    elif old_check_ocr(["师门", "除暴", "副本", "通天塔", "修行"], task_names):
        click(activity_loc[3], text="点击 经验")
    elif old_check_ocr(["刷道", "修法", "师门", "通天塔"], task_names):
        click(activity_loc[4], text="点击 全部")
        xp.swipe(456, 155, 476, 453)  # 下滑
        if "法" in task_names:
            # 上划
            xp.swipe(481, 380, 491, 155, 3.3)
    # 识别任务
    time.sleep(5)
    is_complete = ocr_task(task_names)
    if is_complete == "完成":
        return False
    elif is_complete:
        return True
    elif old_ocr_task(old_task_names):
        return True
    click(main_task["cancel"], text="点击 任务栏叉号")
    return False


# 检测右边框是否处于组队还是任务
def switch_zhudui_renwu(task=True):
    """task 为True 表示放在任务 为False表示组队"""
    # 检测 右侧任务栏是否存在
    taskbar1 = loop_Image_until(mainUI["find_image"]["任务"], times=2)
    if not taskbar1:
        # 检测三角是否存在 检测
        triangle = loop_until(mainUI["find_colors"], "右侧三角标记", times=3)
        if triangle:
            click(mainUI["右侧三角标记"], text="点击 右侧标记")
        else:
            return False
    select_loc = mainUI["main_task_right_loc"]["select"][0]
    select_color1 = mainUI["main_task_right_loc"]["select"][1]
    task_status = xp.matchColor(select_color1, select_loc[0], select_loc[1])
    xp.console("右侧框是否处于任务:", task_status)
    if task_status == task:
        return 1
    elif task_status == True and task == False:
        click(mainUI["main_task_right_loc"]["loc_team"], text="点击 组队")
        cancel = loop_Image_until(mainUI["find_image"]["帮派退出"], times=2)
        if cancel:
            click([cancel.x, cancel.y, cancel.x + 20, cancel.y + 20], text="点击 叉号")
        return 1
    elif (task_status == False) and (task == True):
        click(mainUI["main_task_right_loc"]["loc_task"], text="点击 任务")
        return 1


# 战斗之前应该判断 是否处于非自动战斗状态
# 找到 右下角 自动 进行设置
def battle_use(man_enemy_loc="031",
               pet_enemy_loc="031",
               man_skill_name=None, pet_skill_name=None,
               man_defence=False, pet_defence=False, escape=False, auto=False):
    if isinstance(man_enemy_loc, str):
        man_enemy_loc = battle_setting["enemy_loc"][man_enemy_loc]
    if isinstance(pet_enemy_loc, str):
        pet_enemy_loc = battle_setting["enemy_loc"][pet_enemy_loc]
    if escape:
        click(battle_setting["逃跑"], text="点击 逃跑")
        # 可能会有 死亡提醒确认
        if loop_until(battle_setting["find_color"], "确认", times=3):
            click(battle_setting["确认"], text="点击 确认")
        click(battle_setting["防御"], text="点击 防御")
        return
    # 人物 出手设置
    if man_defence:
        click(battle_setting["防御"], text="点击 防御")
    # 循环检测 道具是否存在
    elif loop_Image_until(battle_setting["find_image"]["道具"], times=2):
        if not man_skill_name:
            click(man_enemy_loc, text="平A %s" % man_enemy_loc)
        else:
            # 点击法术
            click(battle_setting["法术"], text="点击 法术")
            # 找图 点击
            res = loop_Image_until(battle_setting["find_image"][man_skill_name], times=2)
            if res:
                click([res.x, res.y, res.x + res.width, res.y + res.height], text="点击 %s" % man_skill_name)
                # 点击 目标
                click(man_enemy_loc, text="点击 {}".format(man_enemy_loc))
    # 宠物出手
    if pet_defence:
        click(battle_setting["防御"], text="点击 防御")
    elif loop_Image_until(battle_setting["find_image"]["道具"], times=2):
        if not pet_skill_name:
            click(pet_enemy_loc, text="平A %s" % pet_enemy_loc)
        else:
            # 点击法术
            click(battle_setting["法术"], text="点击 法术")
            # 找图 点击
            res = loop_Image_until(battle_setting["find_image"][pet_skill_name], times=2)
            if res:
                click([res.x, res.y, res.x + res.width, res.y + res.height], text="点击 %s" % pet_skill_name)
                # 点击 目标
                click(pet_enemy_loc, text="点击 {}".format(pet_enemy_loc))
            else:
                # 没有法术技能 点击平A
                click(pet_enemy_loc, text="点击 {}".format(pet_enemy_loc))
    # 点击 自动
    if auto:
        click(battle_setting["自动"], text="点击 自动")


# 巡逻栏
def main_patrol_setting(double=False, defence=True, jump=False, man_skill_name="组合技能", pet_skill_name="法攻二阶"):
    '''暂时只设置 人物技能'''
    # 点击 要不要开启？ 看是否为跳转
    if not jump:
        click(mainUI["main_patrol_loc"], text="点击 巡逻位置")
    # 检查双倍
    double_times = ocr(main_patrol["double_nums"])
    xp.console("双倍：{}".format(double_times))
    log.info("双倍：{}".format(double_times))
    # 判断双倍是否开启
    switch_status = xp.matchColor("#63B273", 380, 654)
    xp.console(switch_status)
    if double ^ switch_status:
        click(main_patrol["double_switch"], text="点击 双倍")
    # 开启防御
    if defence:
        click(main_patrol["auto_battle"], text="点击 选择自动技能")
        res_defence = loop_Image_until(main_patrol["find_image"]["防御"], times=3)
        if res_defence:
            click([res_defence.x, res_defence.y, res_defence.x + 15, res_defence.y + 15], text="点击 防御")
        else:
            click(main_patrol["auto_battle"], text="点击 选择自动技能")
    # 开启组合技能
    else:
        click(main_patrol["auto_battle"], text="点击 选择自动技能")
        res_defence = loop_Image_until(main_patrol["find_image"][man_skill_name], times=3)
        if res_defence:
            click([res_defence.x, res_defence.y, res_defence.x + 15, res_defence.y + 15],
                  text="点击 {}".format(man_skill_name))
        else:
            click(main_patrol["auto_battle"], text="点击 选择自动技能")
    # 宠物 技能 法攻二阶
    if pet_skill_name:
        click(main_patrol["auto_pet_battle"], text="点击 选择自动技能")
        res = loop_Image_until(main_patrol["find_image"][pet_skill_name], times=2)
        if res:
            click([res.x, res.y, res.x + 15, res.y + 15], text="点击 {}".format(pet_skill_name))
        else:
            res_a = loop_Image_until(main_patrol["find_image"]["普攻"], times=2)
            if res_a:
                click([res_a.x, res_a.y, res_a.x + 15, res_a.y + 15], text="点击 {}".format("普攻"))
            else:
                click([683, 347, 728, 382], text="点击 宠物普攻")
    # 取消
    click(main_patrol["cancel"], text="点击 叉号")


# 刷道栏
def main_shuadao_setting(first=False, second=False, token_switch=False, add_times=False):
    # 点击
    click(mainUI["main_shuadao_loc"])
    # 刷道令次数
    times = ocr(main_shuadao["times_nums"])
    xp.console(times)  # 零0 可能识别成 o
    if add_times and int(times) < 250:
        click(main_shuadao["setting"])
        click(main_shuadao["add_plus"])
        click(main_shuadao["add_plus"])
        click(main_shuadao["add_plus"])
        click(main_shuadao["use"])
    # 刷道令开关
    switch_status = xp.matchColor("#63B273", 694, 585)
    if switch_status ^ token_switch:
        click(main_shuadao["token_switch"])
    # 一阶降妖
    if first:
        click(main_shuadao["first_order"])
        return
    # 二阶降妖
    if second:
        click(main_shuadao["second_order"])
        return
    # 取消
    click(main_shuadao["cancel"])


# 一阶伏魔
def goto_second_order(token_turn_on=False):
    # 一阶伏魔
    main_shuadao_setting(second=True)
    # 等待与陆压真人对话
    time.sleep(2)
    # 循环找色 陆压真人
    ret = loop_until(second_shuadao["find_color"], "陆压真人")
    if ret:
        person_name = ocr(second_shuadao["person"])
        xp.console("陆压真人检测:", person_name)
        if person_name:
            click(second_shuadao["first"])

            # content = ocr(second_shuadao["content"])
            # if "3" in content:
            #     # 点击离开
            #     click(second_shuadao["leave"])
            #     # 人数不足
            #     # 检查是否需要点击取消
            #     ret = xp.findColor("#E7DFCE", "0|6|#BD966B, 4|14|#AD8A5A, 13|24|#9C7952", 1213, 24, 1254, 62)
            #     if ret:
            #         click(second_shuadao["cancel_dialogue"])
            #         xp.console("点击取消")

            # 是否处于老君查岗
            post_checking = loop_until(second_shuadao["find_color"], "老君查岗", times=3)
            if post_checking:  # 这里报语法错误？
                xp.console("查岗状态:", post_checking)
                res = ocr(second_shuadao["code"]["loc"])
                xp.console("老君查岗:", res)
                count_time = ocr(second_shuadao["code"]["count_time"])
                A = ocr(second_shuadao["code"]["A"])
                B = ocr(second_shuadao["code"]["B"])
                C = ocr(second_shuadao["code"]["C"])
                D = ocr(ocr(second_shuadao["code"]["D"]))
                xp.console("倒计时:%s,%s,%s,%s,%s" % (count_time, A, B, C, D))

            # 检查是否弹出 刷道令 开关
            token_switch = loop_until(second_shuadao["find_color"], "刷道令开关", times=3)
            xp.console("刷道令弹窗:", token_switch)
            if token_switch and not token_turn_on:
                # 点击取消
                xp.console("点击取消")
                click(second_shuadao["cancel_token"])
            else:
                # 点击确认
                xp.console("点击确认")
                click(second_shuadao["confirm_token"])
                # 刷道栏页面 点击 如意刷道令 点击取消
                main_shuadao_setting(token_switch=True)
            # 检测是否处于组队还是任务
            switch_zhudui_renwu(task=True)
            # 点击一阶伏魔
            click(mainUI["main_task_right_loc"]["task_list"][0])
            xp.console("点击任务列表第一个任务")
